using Microsoft.AspNetCore.Mvc;
using JTZY.Model.Batch.Dto;
using JTZY.Model.Batch;
using JTZY.Service.Batch.IBatchService;
using JTZY.Admin.WebApi.Filters;
using JTZY.Model.Product.Dto;
using JTZY.Service.Product.IProductService;
using JTZY.Service.Goods.IGoodsService;
using JTZY.Service.Order.IOrderService;
using JTZY.Service.Order;
using JTZY.Service.Batch;

//创建时间：2025-03-05
namespace JTZY.Admin.WebApi.Controllers.Batch
{
    /// <summary>
    /// 批量发货
    /// </summary>
    [Verify]
    [Route("batch/Batchship")]
    public class BatchshipController : BaseController
    {
        /// <summary>
        /// 批量发货接口
        /// </summary>
        private readonly IBatchshipService _BatchshipService;
        private readonly IProdinfoService _ProdinfoService;
        private readonly ICorecmsuserstockService _usService;
        private readonly ICorecmsbillreshipService _reshipService;
        private readonly IRefshipdetailService _refshipdetailService;
        private readonly ICorecmsbillreshipService _corecmsbillreshipService;
        private readonly ICorecmsbillreshipitemService _refshipitemService;
        private readonly ICorecmsorderitemService _corecmsorderitemService;
        public BatchshipController(IBatchshipService BatchshipService
            , ICorecmsbillreshipService reshipService
            , ICorecmsuserstockService usService
            , IRefshipdetailService refshipdetailService
            , ICorecmsbillreshipService corecmsbillreshipService
            , ICorecmsbillreshipitemService refshipitemService
            , ICorecmsorderitemService corecmsorderitemService
            , IProdinfoService ProdinfoService)
        {
            _BatchshipService = BatchshipService;
            _ProdinfoService = ProdinfoService;
            _usService = usService;
            _reshipService = reshipService;
            _refshipdetailService = refshipdetailService;
            _corecmsbillreshipService = corecmsbillreshipService;
            _refshipitemService= refshipitemService;
            _corecmsorderitemService = corecmsorderitemService;
        }

        /// <summary>
        /// 查询批量发货列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "batchship:list")]
        public IActionResult QueryBatchship([FromQuery] BatchshipQueryDto parm)
        {
            parm.UserId = HttpContext.GetUId();
            var response = _BatchshipService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询批量发货详情
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        [HttpGet("{OrderId}")]
        [ActionPermissionFilter(Permission = "batchship:query")]
        public IActionResult GetBatchship(string OrderId)
        {
            var response = _BatchshipService.GetInfo(OrderId);

            var info = response.Adapt<BatchshipDto>();
            return SUCCESS(info);
        }

        /// <summary>
        /// 添加批量发货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "batchship:add")]
        [Log(Title = "批量发货", BusinessType = BusinessType.INSERT)]
        public IActionResult AddBatchship([FromBody] BatchshipDto parm)
        {
            var modal = parm.Adapt<Batchship>().ToCreate(HttpContext);
            var userId = HttpContext.GetUId();
            var response = _BatchshipService.ToAdd(modal.BatchshipitemNav, modal.BatchshipdeailNav,userId);
            if (!response.status)
            {
                return ToResponse(ResultCode.FAIL, response.msg);
            }
            else
            {
                return SUCCESS(response);
            }
        }

        /// <summary>
        /// 更新批量发货
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "batchship:edit")]
        [Log(Title = "批量发货", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateBatchship([FromBody] BatchshipDto parm)
        {
            var modal = parm.Adapt<Batchship>().ToUpdate(HttpContext);
            var response = _BatchshipService.UpdateBatchship(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除批量发货
        /// </summary>
        /// <returns></returns>
        [HttpPost("delete/{ids}")]
        [ActionPermissionFilter(Permission = "batchship:delete")]
        [Log(Title = "批量发货", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteBatchship([FromRoute] string ids)
        {
            var idArr = Tools.SplitAndConvert<string>(ids);

            return ToResponse(_BatchshipService.Delete(idArr));
        }

        /// <summary>
        /// 查询货物表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost("getprodinfobycode")]
        [ActionPermissionFilter(Permission = "prodinfo:query")]
        public IActionResult GetProdinfoByCode([FromBody] ProdQueryDto param)
        {
            var no = "";
            var f = "";
            if (string.IsNullOrEmpty(param.snCode))
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未检测到物码");

            }
            if (param.snCode.Contains("http"))
            {
                var Querys = UrlStringHelper.GetQueryDictionary(param.snCode);
                if (Querys.Keys.Contains("no"))
                    no = Querys["no"];
                if (Querys.Keys.Contains("n"))
                    no = Querys["n"];
                if (Querys.Keys.Contains("f"))
                    f = Querys["f"];
                if (string.IsNullOrEmpty(f))
                {
                    f = "n";
                }
            }
            else
            {
                no = param.snCode;
            }
            var userId = HttpContext.GetUId();
            var response = _ProdinfoService.GetProdinfoByCode(no, f);
            if (response == null) 
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");

            }

            if (response != null && response.UserId.HasValue && response.UserId.Value > 0 && response.UserId != userId)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此商品不属于您");
            }

            if (response.IsReturn != 1)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此商品非次品");
            }

            if (response.Status == 2)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此商品已出库");
            }

            if (response.Status == 0)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此商品未入库");
            }

           var detail= _refshipdetailService.Queryable().Where(re => re.SnCode == response.SnCode).OrderByDescending(re=>re.Id).First();
            if (detail == null) 
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "未找到此物码的退货商品");
            }

            var reship=_corecmsbillreshipService.Queryable().Where(b => b.ReshipId == detail.ReshipId).First();
            if (reship == null)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此物码未找到退货订单信息");
            }

            var reshipitem = _refshipitemService.Queryable().Where(re => re.ReshipId == reship.ReshipId&&re.ProductId== detail.ProductId).First();
            if (reshipitem == null)
            {
                return ToResponse(ResultCode.CUSTOM_ERROR, "此物码未找到退货订单信息");
            }
            var orderItem = _corecmsorderitemService.Queryable().Where(a => a.Id == reshipitem.OrderItemsId).First();

            var info = response.Adapt<ProdinfoDto>();
            info.AftersalesId = reship.AftersalesId;

            var prod = _usService.Queryable().Where(us => us.UserId == userId && us.ProductId == response.ProductId).First();
            if (prod != null)
            {
                info.BarCode = prod.BarCode;
                info.SkuImage = prod.SkuImage;
                info.SkuName = prod.SkuName;
                info.Sn = prod.Sn;
                info.GoodsId = prod.GoodId;
                info.Price = orderItem.Price;
            }
            return SUCCESS(info);
        }

    }
}